//
//  HEEditAddressViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/12.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEEditAddressViewController.h"
#import "HEAddressInputCell.h"
#import "HEAddressMapViewController.h"

@interface HEEditAddressViewController ()<UITableViewDelegate, UITableViewDataSource, HEAddressInputCellDelegate, BMKGeoCodeSearchDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *formArrs;
@property(nonatomic,strong) BMKGeoCodeSearch *searcher;//编码


@property (nonatomic, strong) BMKLocationManager *locationManager; //定位对象

@end

@implementation HEEditAddressViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.searcher.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.searcher.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = KWhiteColor;
    
    self.title = @"地址管理";
    [self.view addSubview:self.tableView];
    
    if (_type == HEEditAddressTypeAdd) {
        HEReceiveAddressModel *addr = [HEReceiveAddressModel new];
        addr.name = [[UserManager sharedUserManager] getUserInfo].realname;
        addr.phoneNumber = [[UserManager sharedUserManager] getUserInfo].username;
        self.formModel.addressDetails = addr;
    }else {
        self.formModel.addressDetails = _model;
    }
    
    [self initFooterView];
    [self initCell];
    
    if (_type == HEEditAddressTypeAdd) {
        [self startLocation];
    }
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStyleGrouped];
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (void)initFooterView {
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 300)];
    
    // 保存按钮
    QMUIFillButton *saveBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    saveBtn.titleLabel.font = DYBlodFont(15);
    [saveBtn setBackgroundColor:CNavBgColor];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [footerView addSubview:saveBtn];
    [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 设置为默认地址按钮
    QMUIFillButton *defualtBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    defualtBtn.titleLabel.font = DYBlodFont(15);
    [defualtBtn setBackgroundColor:CPriceColor];
    [defualtBtn setTitle:@"设置为默认地址" forState:UIControlStateNormal];
    [footerView addSubview:defualtBtn];
    [defualtBtn addTarget:self action:@selector(setupDefalutClick) forControlEvents:UIControlEventTouchUpInside];
    
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView).mas_offset(30);
        make.left.equalTo(footerView).mas_offset(50);
        make.right.equalTo(footerView).mas_offset(-50);
        make.height.mas_offset(40);
    }];
    
    [defualtBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(saveBtn.mas_bottom).mas_offset(20);
        make.left.equalTo(footerView).mas_offset(50);
        make.right.equalTo(footerView).mas_offset(-50);
        make.height.mas_offset(40);
    }];
  
    self.tableView.tableFooterView = footerView;
}

- (void)saveClick {
    
    if (![self checkAdress]) {
        return;
    }

    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KaddressSave parameters:self.formModel.addressDetails success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            if (self.backBlock) {
                self.backBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)setupDefalutClick {
    if (![self checkAdress]) {
        return;
    }
    
    self.formModel.addressDetails.defaultStatus = YES;
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KaddressSave parameters:self.formModel.addressDetails success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            if (self.backBlock) {
                self.backBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (BOOL)checkAdress {
    BOOL flag = YES;
    if ([DYTools isBlankString:self.formModel.addressDetails.name]) {
        [Dialog toastBottom:@"请填写收货人姓名"];
        flag = NO;
    }
    
    if (![WOValidate valiMobile:self.formModel.addressDetails.phoneNumber]) {
        [Dialog toastBottom:@"请填写正确的手机号码"];
        flag = NO;
    }
    
    if ([DYTools isBlankString:self.formModel.addressDetails.KTitleString]) {
        [Dialog toastBottom:@"请选择所在地区"];
        flag = NO;
    }
    
    if ([DYTools isBlankString:self.formModel.addressDetails.detailAddress]) {
        [Dialog toastBottom:@"请填写详细地址"];
        flag = NO;
    }
    return flag;
}

#pragma mark -

- (void)startLocation {
    [self.locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error) {
            [Dialog toastBottom:@"定位失败，请检查是否打开定位权限"];
        }else {
            BMKLocationReGeocode *model = location.rgcData;
            self.formModel.addressDetails.province = model.province;
            self.formModel.addressDetails.city = model.city;
            self.formModel.addressDetails.region = model.district;
            self.formModel.addressDetails.longitude = location.location.coordinate.longitude;
            self.formModel.addressDetails.latitude = location.location.coordinate.latitude;
            
            self.formModel.addressDetails.KTitleString = nil;
            [self.tableView reloadData];
        }
    }];
}

// 反geo检索 随后调用delegate
- (void)reverseGeoCodeSearch:(CLLocationCoordinate2D)centerCoordinate {
    
    [[Dialog Instance] showCenterProgressWithLabel:@"正在检索地区..."];
    
    // 反geo检索 随后调用delegate
    BMKReverseGeoCodeSearchOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeSearchOption alloc]init];
    reverseGeocodeSearchOption.location = centerCoordinate;
    BOOL flag = [self.searcher reverseGeoCode:reverseGeocodeSearchOption];
    if(flag) {
        
        NSLog(@"反geo检索发送成功");
    } else {
        [[Dialog Instance] hideHUD];
        NSLog(@"反geo检索发送失败");
    }
}

- (BMKGeoCodeSearch *)searcher{
    if (!_searcher) {
        _searcher =[[BMKGeoCodeSearch alloc]init];
    }
    return _searcher;
}


#pragma mark - BMKGeoCodeSearchDelegate
//接收反向地理编码结果
- (void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error {
    [[Dialog Instance] hideHUD];
    if (error == BMK_SEARCH_NO_ERROR) {
        self.formModel.addressDetails.detailAddress = [NSString stringWithFormat:@"%@%@%@", [DYTools IsNotNull: result.addressDetail.streetName],[DYTools IsNotNull:self.formModel.addressDetails.addressTitle],[DYTools IsNotNull: result.addressDetail.streetNumber]];
        _formModel.addressDetails.areaId = result.addressDetail.adCode;
        [self.tableView reloadData];
    }
}

#pragma mark -
- (void)initCell {
    // 总段
    _sections = [NSMutableArray array];

    NSMutableArray *classArr = [NSMutableArray array];

    // 收货人
    GDFiterCellModel *nameModel = [GDFiterCellModel new];
    nameModel.cellKlass = HEAddressInputCell.class;
    nameModel.cellType = GDFiterCellTypeSettingPublic;
    nameModel.leftTitle = @"收货人";

    // 手机号码
    GDFiterCellModel *phoneModel = [GDFiterCellModel new];
    phoneModel.cellKlass = HEAddressInputCell.class;
    phoneModel.cellType = GDFiterCellTypeSettingPublic;
    phoneModel.leftTitle = @"手机号码";

    // 地址
    GDFiterCellModel *addressModel = [GDFiterCellModel new];
    addressModel.cellKlass = HEAddressInputCell.class;
    addressModel.cellType = GDFiterCellTypeSettingPublic;
    addressModel.leftTitle = @"所在地区";

    // 详细地址
    GDFiterCellModel *addrDetailsModel = [GDFiterCellModel new];
    addrDetailsModel.cellKlass = HEAddressInputCell.class;
    addrDetailsModel.cellType = GDFiterCellTypeSettingPublic;
    addrDetailsModel.leftTitle = @"详细地址";
    
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[nameModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    [_sections addObject:nameModel];
    [_sections addObject:phoneModel];
    [_sections addObject:addressModel];
    [_sections addObject:addrDetailsModel];

    [_tableView reloadData];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _sections.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
 
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
               [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
    }];
}

#pragma mark -

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 15)];
    v.backgroundColor = CViewBgColor;
    return v;
}

#pragma mark 解决cell分割线左侧留空的问题
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 下面这几行代码是用来设置cell的上下行线的位置
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    //按照作者最后的意思还要加上下面这一段，才能做到底部线控制位置，所以这里按stackflow上的做法添加上吧。
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

#pragma mark - HEAddressInputCellDelegate
- (void)selectAddressWithMap:(HEReceiveAddressModel *)model {
    HEAddressMapViewController *vc = [HEAddressMapViewController new];
    vc.model = model;
    [vc selectAddress:^(HEReceiveAddressModel * _Nonnull model) {
        
        self.formModel.addressDetails.province = model.province;
        self.formModel.addressDetails.city = model.city;
        self.formModel.addressDetails.region = model.region;
        self.formModel.addressDetails.detailAddress = model.detailAddress;
        self.formModel.addressDetails.longitude = model.longitude;
        self.formModel.addressDetails.latitude = model.latitude;
        self.formModel.addressDetails.addressTitle = model.addressTitle;
        self.formModel.addressDetails.KTitleString = nil;

        [self.tableView reloadData];
        
        [self reverseGeoCodeSearch: CLLocationCoordinate2DMake(self.formModel.addressDetails.latitude, self.formModel.addressDetails.longitude)];
    }];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - lazyLoad

- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置delegate
        _locationManager.delegate = self;
        //设置返回位置的坐标系类型
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设置距离过滤参数
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        //设置预期精度参数
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置应用位置类型
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //设置是否自动停止位置更新
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        //设置是否允许后台定位
        //_locationManager.allowsBackgroundLocationUpdates = YES;
        //设置位置获取超时时间
        _locationManager.locationTimeout = 10;
        //设置获取地址信息超时时间
        _locationManager.reGeocodeTimeout = 10;
    }
    return _locationManager;
}

@end
